package CSSapp::Controller::Css;

use strict;
use warnings;
use base 'Catalyst::Controller::HTML::FormFu';

use Carp qw/ croak /;

=head1 NAME

CSSapp::Controller::CSS - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut


sub edit : Local : FormConfig {
    my ( $self, $c, $id ) = @_;

    my $form   = $c->stash->{form};
    my $params = $form->params;

    # stop too many being added
    $self->deny( $c, "can't add any more css" )
        if !$params->{id} && $self->over_limit($c);

    # stop people editing the defaults
    $self->deny( $c, 'not allowed to edit this css record' )
        if $id && $self->protected_id($id);

    if ( $form->submitted_and_valid ) {
        my $row = $params->{id} 
            ? $c->model('DB')->resultset('Css')->find({ id => $params->{id} })
            : $c->model('DB')->resultset('Css')->new({});
        
        $form->model->update( $row );
        
        $c->res->redirect( $c->uri_for('/') );
    }
    elsif ( !$form->submitted && $id ) {
        my ($row) = $c->model('DB')->resultset('Css')->find($id);
        
        if ($row) {
            my $form = $c->stash->{form};
            $form->model->default_values( $row );
        }
    }

    return;
}

sub delete : Local : Args(1) : FormConfig {
    my ( $self, $c, $id ) = @_;

    # stop people deleting the defaults
    $self->deny( $c, 'not allowed to delete this css record' )
        if $self->protected_id($id);
    
    my $form = $c->stash->{form};

    if ( $form->submitted_and_valid ) {
        my $params = $form->params;
        
        my $css = $c->model('DB')->resultset('Css')->find( $params->{id} );
        
        $css->delete if $css;
        
        $c->res->redirect( $c->uri_for('/') );
    }
    elsif ( !$form->submitted ) {
        $c->stash->{form}->get_field('id')->value( $id );
    }

    return;
}

sub view : Local : Args(1) {
    my ( $self, $c, $id ) = @_;
    
    my $row = $c->model('DB')->resultset('Css')->find({ id => $id })
        or croak 'css id not found';
    
    $c->res->content_type('text/css');
    $c->res->body( $row->css );
    
    return;
}

sub protected_id : Private {
    my ( $self, $id ) = @_;
    
    return grep { $id == $_ } (1, 2);
}

sub over_limit : Private {
    my ( $self, $c ) = @_;
    
    my $rs = $c->model('DB')->resultset('Css')->search(
    {},
    {
        select => [
            { count => '*' }
        ],
        as => ['count'],
    });
    
    my $count = $rs->count;
    
    return ( $count > 50 ) ? 1 : 0;
}

sub deny : Private {
    my ( $self, $c, $message ) = @_;
    
    $message = 'access denied' if !defined $message;
    
    $c->res->body($message);
    
    $c->detach;
}


=head1 AUTHOR

Carl Franks

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
